package com.ruoyi.system.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.system.DTO.Reques.vms.SkuDTO;
import com.ruoyi.system.DTO.Reques.vms.SkuSearchDTO;
import com.ruoyi.system.DTO.Reques.vms.SkuUpdateDto;
import com.ruoyi.system.mapper.SkuClassDao;
import com.ruoyi.system.mapper.SkuDao;
import com.ruoyi.system.pojo.vms.SkuClassEntity;
import com.ruoyi.system.pojo.vms.SkuEntity;
import com.ruoyi.system.service.SkuService;
import com.ruoyi.system.utils.ExcelUtil;
import com.ruoyi.system.utils.MinioUtil;
import com.ruoyi.system.vo.vms.PageVO;
import com.ruoyi.system.vo.vms.SkuClassVO;
import com.ruoyi.system.vo.vms.SkuVO;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.utils.IdGenerator;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description:
 *
 * @author JourWon
 * @date Created on 2025/5/13
 */
@Service
public class SkuServiceImpl implements SkuService {

    @Autowired
    private SkuDao skuDao;

    @Autowired
    private SkuClassDao skuClassDao;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private MinioUtil minioUtil;

    @DS(value = "slave")
    @Override
    public PageVO<SkuVO> search(SkuSearchDTO searchDTO) {
        // 参数处理
        Integer pageIndex = searchDTO.getPageIndex() == null ? 1 : searchDTO.getPageIndex();
        Integer pageSize = searchDTO.getPageSize() == null ? 10 : searchDTO.getPageSize();

        // 构建查询条件
        QueryWrapper<SkuEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(searchDTO.getSkuName())) {
            queryWrapper.like("sku_name", searchDTO.getSkuName());
        }
        if (searchDTO.getClassId() != null) {
            queryWrapper.eq("class_id", searchDTO.getClassId());
        }

        // 分页查询
        Page<SkuEntity> page = new Page<>(pageIndex, pageSize);
        IPage<SkuEntity> skuPage = skuDao.selectPage(page, queryWrapper);

        // 转换为VO
        List<SkuVO> skuVOs = skuPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        // 构建返回结果
        PageVO<SkuVO> pageVO = new PageVO<>();
        pageVO.setPageIndex(pageIndex);
        pageVO.setPageSize(pageSize);
        pageVO.setTotalCount(skuPage.getTotal());
        pageVO.setTotalPage((int) skuPage.getPages());
        pageVO.setCurrentPageRecords(skuVOs);

        return pageVO;
    }

    @Override
    @DS(value = "slave")
    @Transactional
    public Boolean create(SkuDTO skuDTO) {
        // 1. 校验商品名称唯一性
        LambdaQueryWrapper<SkuEntity> nameQuery = new LambdaQueryWrapper<>();
        nameQuery.eq(SkuEntity::getSkuName, skuDTO.getSkuName());
        if (skuDao.selectCount(nameQuery) > 0) {
            throw new ServiceException("商品名称已存在");
        }

        // 2. 校验商品类别是否存在
        if (skuClassDao.selectById(skuDTO.getClassId()) == null) {
            throw new ServiceException("商品类别不存在");
        }

        // 3. 转换DTO为Entity
        SkuEntity entity = new SkuEntity();
        entity.setSkuId(idGenerator.nextId());
        entity.setSkuName(skuDTO.getSkuName());
        entity.setSkuImage(skuDTO.getSkuImage());
        entity.setPrice(skuDTO.getPrice());
        entity.setClassId(skuDTO.getClassId());
        entity.setUnit(skuDTO.getUnit());
        entity.setBrandName(skuDTO.getBrandName());
        entity.setIsDiscount(false); // 默认不打折
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());

        // 4. 插入数据库
        return skuDao.insert(entity) > 0;
    }

    @DS(value = "slave")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSku(Long skuId, SkuUpdateDto updateDto) {
        // 检查商品是否存在
        SkuEntity existingSku = skuDao.selectById(skuId);
        if (existingSku == null) {
            throw new ServiceException("商品不存在");
        }

        // 检查商品名称是否已被其他商品使用
        SkuEntity sameNameSku = skuDao.selectBySkuNameExcludeId(
                updateDto.getSkuName(), skuId);
        if (sameNameSku != null) {
            throw new ServiceException("商品名称已被使用");
        }

        // 转换DTO为实体
        SkuEntity sku = new SkuEntity();
        BeanUtils.copyProperties(updateDto, sku);
        sku.setSkuId(skuId);

        // 更新商品
        int affectedRows = skuDao.updateSku(sku);
        return affectedRows > 0;
    }

    @DS(value = "slave")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer importSkus(MultipartFile file, boolean overwrite) {
        try {
            // 解析Excel文件
            List<SkuEntity> skuList = ExcelUtil.parseSkuExcel(file);

            int successCount = 0;

            // 批量处理商品数据
            for (SkuEntity sku : skuList) {
                try {
                    SkuEntity existingSku = skuDao.selectBySkuName(sku.getSkuName());

                    if (existingSku != null) {
                        if (overwrite) {
                            // 覆盖模式 - 更新现有商品
                            sku.setSkuId(existingSku.getSkuId());
                            skuDao.updateSku(sku);
                            successCount++;
                        }
                        // 非覆盖模式 - 跳过已有商品
                    } else {
                        // 新增商品
                        skuDao.insert(sku);
                        successCount++;
                    }
                } catch (Exception e) {
                    // 记录错误但继续处理其他数据
                    // 实际项目中可以记录更详细的错误日志
                }
            }

            return successCount;
        } catch (IOException e) {
            throw new ServiceException("解析Excel文件失败");
        }
    }

    private SkuVO convertToVO(SkuEntity entity) {
        SkuVO vo = modelMapper.map(entity, SkuVO.class);

        // 查询商品分类信息
        SkuClassEntity classEntity = skuClassDao.selectById(entity.getClassId());
        if (classEntity != null) {
            vo.setSkuClass(modelMapper.map(classEntity, SkuClassVO.class));
        }

        return vo;
    }
}
